package com.zbkj.admin.task.mszs;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qcloud.cos.utils.Md5Utils;
import com.qiniu.util.StringUtils;
import com.zbkj.common.model.mszs.MszsHotel;
import com.zbkj.common.model.mszs.MszsOrder;
import com.zbkj.common.model.mszs.MszsRoom;
import com.zbkj.common.utils.DateUtil;
import com.zbkj.service.service.sms.SmsService;
import com.zbkj.service.service.mszs.MszsHotelService;
import com.zbkj.service.service.mszs.MszsOrderService;
import com.zbkj.service.service.mszs.MszsRoomService;
import com.zbkj.service.service.mszs.QimoWebCallService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 七陌-自动回拨task
 * @author lingfe
 */
@Slf4j
@Component
@Configuration //读取配置
@EnableScheduling // 2.开启定时任务
public class QimoCallBackTask {

    @Autowired
    private MszsHotelService mszsHotelService;

    @Autowired
    private MszsOrderService mszsOrderService;

    @Autowired
    private QimoWebCallService qimoWebCallService;

    @Autowired
    private MszsRoomService roomService;

    @Autowired
    private SmsService smsService;

    public static void main(String[] args) throws UnsupportedEncodingException {
        //账户编号：https://developer.7moor.com/dc/#/other/data
        String account ="N00000062079";
        //账号接口密钥、令牌
        String aPISecret="083e6fc0-8843-11ee-afa3-af35c7ab7e65";
        //时间戳
        String datetimeStr = DateUtil.nowDate("yyyyMMddHHmmss");

        //生成请求头action
        StringBuffer authBuffer=new StringBuffer();
        authBuffer.append(account).append(":").append(datetimeStr);
        String strAuthorization = Base64.encode(authBuffer.toString(),"utf-8");

        //生成签名-sig
        StringBuffer sigBuffer=new StringBuffer();
        sigBuffer.append(account).append(aPISecret).append(datetimeStr);
        String sig=Md5Utils.md5Hex(sigBuffer.toString());

        //1、向七陌-发送回拨请求,
        StringBuffer url=new StringBuffer();
        url.append("https://apis.7moor.com/v20160818/webCall/webCall/");
        url.append(account);
        url.append("?sig=").append(sig.toUpperCase());

        //设置参数
        Map<String,Object> mapParam=new HashMap<>();
        //固定值
        mapParam.put("Action","Webcall");
        //虚拟服务号
        mapParam.put("ServiceNo","0101112170");
        //被呼手机号
        mapParam.put("Exten","18212620440");
        //接听语音
        mapParam.put("Variable","name:熙喆酒店民宿");
        //mapParam.put("Variable","text:\"你好，我们是熙喆酒店民宿，欢迎您的入住！\"");
        //发起请求，返回响应结果
        String paramJson = JSON.toJSONString(mapParam);
        log.info("url:{}",url);
        log.info("paramJson:{}",paramJson);

        try {
            StringEntity requestEntity = new StringEntity(paramJson,"utf-8");
            HttpClientBuilder builder = HttpClientBuilder.create();
            CloseableHttpClient client = builder.build();
            HttpPost post = new HttpPost(url.toString());
            post.addHeader("Accept", "application/json");
            post.addHeader("Content-Type", "application/json;charset=utf-8");
            post.addHeader("Authorization", strAuthorization);
            post.setEntity(requestEntity);
            CloseableHttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            log.info("the response is : " + EntityUtils.toString(entity, "utf8"));
        } catch (Exception var20) {
            var20.printStackTrace();
        }
        //String response = HttpUtil.createPost(url.toString()).addHeaders(headerMap).form(requestEntity).execute().body();
        //log.info(response);
    }

    /**
     * 判断当前时间是否大于某个时点
     * @param time HH:mm:ss
     * @return
     */
    public static boolean timeCompare(String time){
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
        LocalTime localTime=LocalTime.parse(time,dtf);
        return LocalTime.now() .isAfter(localTime);
    }

    //@Scheduled(cron = "0 */1 * * * ?") //每分钟执行一次
    //@Scheduled(fixedDelay = 1000 * 20L) //20s-同步一次数据
    public void init(){
        log.info("---QimoCallBackTask---七陌-自动回拨task: Execution Time - {}", DateUtil.nowDateTime());
        try {
            //得到酒店信息list
            List<MszsHotel> hotelList = mszsHotelService.list( );
            List<String> hotelIds=new ArrayList<>();
            Map<String,String> mapHotel = new HashMap<>();
            //使用 Iterator 遍历
            Iterator<MszsHotel> hotelListIterator = hotelList.iterator();
            while (hotelListIterator.hasNext()) {
                MszsHotel item = hotelListIterator.next();
                //验证酒店自动回拨时间设置
                boolean bl=true;
                switch (item.getIsCallTime()){
                    case 1: bl = false;
                    case 2: if(timeCompare("09:00:00")&&timeCompare("18:00:00")) bl = false ; break;
                    case 3: if(timeCompare("18:00:00")||!timeCompare("09:00:00")) bl = false; break;
                    case 4: //时间段
                        bl = false;
                        break;
                }
                if(bl){
                    hotelListIterator.remove();
                }else{
                    hotelIds.add(item.getId());
                    mapHotel.put(item.getId(),item.getJdName());
                }
            }
            if(hotelList.isEmpty()){
                log.info("---QimoCallBackTask---七陌-自动回拨task: hotelList-siz：{},不再继续处理！", 0);
                return;
            }

            //定义查询酒店订单对象
            LambdaQueryWrapper<MszsOrder> orderQW=new LambdaQueryWrapper<>();
            orderQW.in(MszsOrder::getJdId,hotelIds);
            orderQW.eq(MszsOrder::getOrderStatusNumber,1);//待入住
            orderQW.eq(MszsOrder::getRoomId,0);
            //获取酒店订单信息
            List<MszsOrder> orderList = mszsOrderService.list(orderQW);
            orderList.forEach(order->{
                //1、分配房间,获取一条未入住的房间信息,并绑定订单同时更新房间状态
                MszsRoom mszsRoom = roomService.getWhereStatusOne(order.getJdId(),0);
                if(mszsRoom != null) {
                    //订单绑定房间,同时更新订单状态
                    order.setRoomId(mszsRoom.getId());
                    order.setOrderStatus("已入住");
                    order.setOrderStatusNumber(2);
                    mszsOrderService.updateById(order);
                    //更新房间状态,更改为"已入住=2"
                    mszsRoom.setStatus(2);
                    roomService.updateById(mszsRoom);
                }else{
                    log.info("---QimoCallBackTask---获取一条未入住的房间信息: 没有空房间！");
                    //通知商家-没有空房间
                    //MszsHotel mszsHotel = mszsHotelService.getById(order.getJdId());
                    //if(mszsHotel==null)return;
                    //smsService.sendRoomNullCode(mszsHotel.getJdPhone(),mszsHotel.getJdName(),order.getGmPt(),1019481057);
                }
                //验证-订单是否绑定用户号码
                if(StringUtils.isNullOrEmpty(order.getUserPhone())){
                    log.info("订单：{}，未绑定用户手机号，不发送。",order.getOrderNo());
                    return;
                }

                //2、向七陌-发送回拨请求
                //qimoWebCallService.qimoCallRequestSet(order.getUserPhone(), mapHotel.get(order.getJdId()));
                //3、发送短信
                //qimoWebCallService.sendRoomInfoSms(order.getUserPhone(),mszsRoom);
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("---QimoCallBackTask---七陌-自动回拨task-发生错误:" + " | msg : " + e.getMessage());
        }

    }


}
